package com.example.yuntiku.Email;

import com.sun.mail.util.MailSSLSocketFactory;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.security.GeneralSecurityException;
import java.util.Properties;
import java.util.Random;

public class SendEmail {
    private final static String AuthorizationCode = "hizqgebfsiuqdchg";       //16位授权码

    private final static String Sender = "2770532577@qq.com";                  //发件人

    public String generateCaptcha(){
        StringBuilder stringBuilder = new StringBuilder();
        Random random = new Random();
        for (int i = 0;i < 5;i++){
            int rangeInt = random.nextInt(90 - 65 + 1) + 65;
            stringBuilder.append((char) rangeInt);
        }
        return stringBuilder.toString();
    }

    public String send(String Recipients,String Captcha) throws GeneralSecurityException, MessagingException {
        //创建一个配置文件并保存
        Properties properties = new Properties();
        properties.setProperty("mail.host","smtp.qq.com");
        properties.setProperty("mail.transport.protocol","smtp");
        properties.setProperty("mail.smtp.auth","true");

            //QQ存在一个特性设置SSL加密


            MailSSLSocketFactory sf = new MailSSLSocketFactory();
            sf.setTrustAllHosts(true);
            properties.put("mail.smtp.ssl.enable", "true");
            properties.put("mail.smtp.ssl.socketFactory", sf);

        //创建一个session对象
        Session session = Session.getDefaultInstance(properties, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(Sender,AuthorizationCode);
            }
        });

        //开启debug模式
        session.setDebug(true);

        //获取连接对象
        Transport transport = session.getTransport();

        //连接服务器
        transport.connect("smtp.qq.com",Sender,AuthorizationCode);

        //创建邮件对象
        MimeMessage mimeMessage = new MimeMessage(session);

        //邮件发送人
        mimeMessage.setFrom(new InternetAddress(Sender));

        //邮件接收人
        mimeMessage.setRecipient(Message.RecipientType.TO,new InternetAddress(Recipients));

        //邮件标题
        mimeMessage.setSubject("账号验证码: " + Captcha);

        //邮件内容
        mimeMessage.setContent("您好，这是注册验证码：" + "<b>" + Captcha + "</b>","text/html;charset=UTF-8");

        //发送邮件
        transport.sendMessage(mimeMessage,mimeMessage.getAllRecipients());

        //关闭连接
        transport.close();

        //返回验证码
        return Captcha;
    }
}
